import React, { useEffect, useState } from "react";
import "./Bus.css";
import {
  message, Spin, Empty,
  Table, Button, Space,
  Drawer, Form, Input,
  InputNumber, Select,
} from 'antd';
import { 
  giveRequest,
  getbusinfo,
  deletebus,
  modifybusinfo,
  addbus,
  allline,
  modifybusinline,
  deletebusinline,
} from "../../../lib/apiconfig";

const { Column } = Table;
const { Option } = Select;
const ld_data = [
  {
    longitude: 118.752746, 
    dimensionality: 36.716443
  },
  {
    longitude: 118.907727, 
    dimensionality: 36.662841
  },
  {
    longitude: 118.95674,
    dimensionality: 36.752525
  }
];

/**
 * @description 关于公交车的管理组件
 */
const Bus = () => {
  const [data, setData] = useState(undefined);
  const [lineData, setLineData] = useState(undefined);
  const [drawer, setDrawer] = useState(false);
  const [freshAction, setFreshAction] = useState(false);
  const [title, setTitle] = useState("新增车辆");
  const [currentMsg, setCurrentMsg] = useState({ licence: "", maxload: 0, faultcondition: "否", lineid: "", linename: "", lineChange: false });
  const [form] = Form.useForm();


  useEffect(() => {
    giveRequest(getbusinfo(0,1000), "GET", null, res => {
      const status = res.status;
      if ( status === "fail" ) {
        message.error("获取数据失败");
        setData(null);
      } else {
        res.data.forEach(item => {
          item["key"] = item.licence;

          if ( item.faultcondition === 0 )
            item.faultcondition = "否";
          else
            item.faultcondition = "是";

          if ( item.runningcondition === 0 )
            item.runningcondition = "否";
          else
            item.runningcondition = "是";

          if ( item.linename === null ) {
            item.linename = "无";
            item.lineid = "";
          }
        });
        setData(res.data);

        giveRequest(allline, "GET", null, res => {
          const status = res.status;
          if ( status === "fail" ) {
            message.error("获取数据失败");
            setLineData(null);
          } else {
            res.data.forEach(item => {
              item["key"] = item.id;
            });
            setLineData(res.data);
          }
        });
      }
    });
  }, [freshAction]);

  // 新增车辆
  const newBus = () => {
    const message = { licence: "", maxload: 0, faultcondition: "否", lineid: "", linename: "", lineChange: true };
    setTitle("新增车辆");
    setCurrentMsg(message);
    form.setFieldsValue(message);
    setDrawer(true);
  }

  // 修改公交车信息
  const modifyBusInfo = record => {
    const message = { licence: record.licence, maxload: record.maxload, faultcondition: record.faultcondition, 
                      lineid: record.lineid, linename: record.linename, lineChange: false };
    setTitle("修改车辆信息");
    setCurrentMsg(message);
    form.setFieldsValue(message);
    setDrawer(true);
  };

  // 删除车辆
  const deleteBus = record => {
    giveRequest(
      deletebus,
      "POST",
      {
        status: "deletebus",
        data: {
          licence: record.licence,
        }
      },
      res => {
        const status = res.status;
        if ( status === "success" ) {
          message.success("删除成功");
          setFreshAction(!freshAction);
        } else {
          message.error("删除失败!");
        }
      }
    );
  };
  
  // 提交表单
  const submit = () => {
    if ( currentMsg && currentMsg.licence && currentMsg.maxload && currentMsg.faultcondition ) {
      if ( title === "修改车辆信息" ) {
        var data = {
          licence: currentMsg.licence,
          maxload: currentMsg.maxload,
          faultcondition: currentMsg.faultcondition === "是" ? 1 : 0,
        };
        if ( currentMsg.faultcondition === "是" ) {
          data = Object.assign(data, {
            runningcondition: 0,
            speed: 0,
            busload: 0,
          });
        }
        giveRequest(
          modifybusinfo,
          "POST",
          {
            status: "modifybusinfo",
            data: data
          },
          res => {
            const status = res.status;

            if ( status === "success" ) {
              if ( currentMsg.lineChange === true ) {
                if ( currentMsg.lineid ) {
                  giveRequest(
                    modifybusinline,
                    "POST",
                    {
                      status: "modifybusinline",
                      data: {
                        licence: currentMsg.licence,
                        lineid: currentMsg.lineid
                      }
                    },
                    res => {
                      const status = res.status;
                      if ( status === "success" ) {
                        message.success("修改成功");
                        setDrawer(false);
                        setFreshAction(!freshAction);
                      } else {
                        message.error("修改失败!");
                      }
                    }
                  );
                } else {
                  giveRequest(
                    deletebusinline,
                    "POST",
                    {
                      status: "deletebusinline",
                      data: {
                        licence: currentMsg.licence,
                      }
                    },
                    res => {
                      const status = res.status;
                      if ( status === "success" ) {
                        message.success("修改成功");
                        setDrawer(false);
                        setFreshAction(!freshAction);
                      } else {
                        message.error("修改失败!");
                      }
                    }
                  );
                }
              } else {
                message.success("修改成功");
                setDrawer(false);
                setFreshAction(!freshAction);
              }
            } else if ( status === "fail" ) {
              message.error("修改失败!");
            }
          }
        );
      } else if ( title === "新增车辆" ) {
        giveRequest(
          addbus,
          "POST",
          {
            status: "addbus",
            data: {
              licence: currentMsg.licence,
              maxload: currentMsg.maxload,
              faultcondition: currentMsg.faultcondition === "是" ? 1 : 0,
              pindex: 0,
              longitude: currentMsg.lineid <= 3 && currentMsg.lineid >= 1 ? ld_data[currentMsg.lineid-1].longitude : ld_data[2].longitude,
              dimensionality: currentMsg.lineid <= 3 && currentMsg.lineid >= 1 ? ld_data[currentMsg.lineid-1].dimensionality : ld_data[2].dimensionality,
            }
          },
          res => {
            const status = res.status;

            if ( status === "success" ) {
              if ( currentMsg.lineid ) {
                giveRequest(
                  modifybusinline,
                  "POST",
                  {
                    status: "modifybusinline",
                    data: {
                      licence: currentMsg.licence,
                      lineid: currentMsg.lineid,
                    }
                  },
                  res => {
                    const status = res.status;
                    if ( status === "fail" ) {
                      message.error("添加失败!");
                    } else {
                      message.success("添加成功");
                      setDrawer(false);
                      setFreshAction(!freshAction);
                    }
                  }
                );
              } else {
                message.success("添加成功");
                setDrawer(false);
                setFreshAction(!freshAction);
              }
            } else if ( status === "fail" ) {
              message.error("添加失败!");
            } else if ( status === "warning" ) {
              message.warn("该车辆已存在!");
            }
          }
        );
      }
    } else {
      message.warn("车辆信息不能为空!");
    }
  };


  return (
    <div className="Bus-page">
    { function() {
      if ( data === undefined )
        return (
          <div className="Bus-loading flex-column-center-center">
            <Spin size="large" />
          </div>
        );
      else if ( data === null ) 
        return (
          <div className="Bus-failed flex-column-center-center">
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          </div>
        );
      else
        return (
          <div className="Bus-content flex-column-center-center">
            <Table dataSource={data} className="Bus-table" pagination={{ pageSize: 9, style: { marginRight: "30px" } }}>
              <Column title="车牌号" dataIndex="licence" key="licence" />
              <Column title="路线" dataIndex="linename" key="linename" />
              <Column title="最大载客量" dataIndex="maxload" key="maxload" />
              <Column title="现有载客量" dataIndex="busload" key="busload" />
              <Column title="故障状况" dataIndex="faultcondition" key="faultcondition" />
              <Column title="运行状况" dataIndex="runningcondition" key="runningcondition" />
              <Column title="运行时速" dataIndex="speed" key="speed" />
              <Column
                title="操作"
                key="action"
                render={record => (
                  <Space size="middle">
                    <Button 
                      type="link"
                      style={{ padding: 0 }}
                      onClick={() => modifyBusInfo(record)}
                    >
                      修改信息
                    </Button>
                    <Button 
                      type="link"
                      style={{ padding: 0 }}
                      onClick={() => deleteBus(record)}
                    >
                      删除车辆
                    </Button>
                  </Space>
                )}
              />
            </Table>
            <div className="Bus-new-account flex-row-start-center">
              <Button 
                type="primary" 
                size="large" 
                style={{ width: 150 }}
                onClick = {() => newBus()}
              >
                新增车辆
              </Button>
            </div>
            <Drawer
              title={title}
              width={360}
              onClose={() => setDrawer(false)}
              visible={drawer}
              footer={
                <div style={{ textAlign: 'right' }}>
                  <Button 
                    style={{ marginRight: 16, width: 80 }}
                    onClick={() => setDrawer(false)}
                  >
                    取消
                  </Button>
                  <Button 
                    type="primary"
                    style={{ width: 80 }}
                    onClick={submit}
                  >
                    提交
                  </Button>
                </div>
              }
            >
              <Form 
                layout="vertical" 
                hideRequiredMark
                form={form}
                onValuesChange={data => {
                  const new_bus_info = JSON.parse(JSON.stringify(currentMsg));
                  Object.keys(data).forEach(item => {
                    new_bus_info[item] = data[item];
                    if ( item === "lineid" )
                      new_bus_info.lineChange = true;
                  });
                  setCurrentMsg(new_bus_info);
                }}
              >
                <Form.Item label="车牌号" name="licence" rules={[{ required: true, message: "车牌号不能为空!" }]}>
                  { title === "修改车辆信息" ? (
                    <Input disabled />
                  ) : (
                    <Input placeholder="请输入车牌号~" />
                  )}
                </Form.Item>
                <Form.Item label="最大载客量" name="maxload" rules={[{ required: true, message: "最大载客量不能为空!" }]}>
                  <InputNumber min={0} />
                </Form.Item>
                <Form.Item label="是否故障" name="faultcondition" rules={[{ required: true, message: "请选择故障状况!" }]}>
                  <Select>
                    <Option value="否">否</Option>
                    <Option value="是">是</Option>
                  </Select>
                </Form.Item>
                <Form.Item label="运行路线" name="lineid">
                  <Select>
                    <Option value="" key={"000"}>无</Option>
                    { function() {
                      if ( lineData ) {
                        return lineData.map(item => {
                          return (
                            <Option value={item.id} key={item.key}>{item.name}</Option>
                          );
                        });
                      } else {
                        return null;
                      }
                    } ()}
                  </Select>
                </Form.Item>  
              </Form>
            </Drawer>
          </div>
        );
    } ()}
    </div>
  );
}

export default Bus;